#include "app_router.h"
#include "log/log.h"
#include "app_mqtt1.h"
#include "app_message.h"
#define DEVICE_LIST_SIZE 10

 static int router_send_msg(Device *device ,char *data,int len){

 
   //将data转换成json格式字符串
   Message *message =  app_message_initByBinary(data,len);
   char json[128];
   int len = app_message_toJSON(message,json,sizeof(json));
   app_mqtt_send(json,len);

   app_message_free(message);

   return 0;
 
 }
 static int router_recv_callback(char *json,int len){
    //将json转换成Message
    Message *message = app_message_initByJSON(json);
    for (int i = 0; i < device_count; i++)
    {
        // 当前是通过连接类型来匹配的
        if (message->conn_type == device_list[i]->conn_type)
        {
            // 将message转换为二进制数据
            char binary[128];
            int len = app_message_toBinary(message, binary, sizeof(binary));
            int result = app_device_recvMessage(device_list[i], binary, len);
            free(message);
            return result;
        }
    }

    log_error("没有找到对应的设备");
    return -1;

 }

static Device *device_list[DEVICE_LIST_SIZE];
static int device_count = 0;

int app_router_init(){

app_mqtt_init();

app_mqtt_registRecvCallback(router_recv_callback);

    return  0;
}

void app_router_close(){

    app_mqtt_close();
    for (int i = 0; i < device_count; i++)
    {
        app_device_stop(device_list[i]);
        app_device_close(device_list[i]);
    }
    
}

int app_router_registerDevice(Device *device){
    if(device_count >= DEVICE_LIST_SIZE){
        log_error("Device list is full");
        return -1;
    }
    //给设备指定为实现发送消息的函数
    device->func->send_msg = router_send_msg;

    device_list[device_count++] = device;
    //启动设备
    app_device_start(device);

    return 0;
}